<?php
// +----------------------------------------------------------------------
// | Author: yaoyihong <510974211@qq.com>
// +----------------------------------------------------------------------
namespace addon\mall\logic;
use app\common\logic\LogicBase;
use \tpfcore\Core;
use think\Db;
use \tpfcore\helpers\StringHelper;

class Goods extends LogicBase
{
	public function getGoods($data=[]){
		return Core::loadAddonModel($this->name)->getList($data);
	}
	public function saveGoods($data){
		$validate=Core::addonValidate($this->name);
        $validate_result = $validate->scene("add")->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $validate->getError(), null];
        }
        /* 自动生成缩略图 */
        if(isset($data['auto_thumb']) && !empty($data['auto_thumb']) && !empty($data['goods_img'])){

			$data['goods_thumb']=$this->explode_thumb($data['goods_img']);

        }

        /* 是否有促销 */
        if(!isset($data['is_promote'])){
        	unset($data['promote_start_date']);
        	unset($data['promote_end_date']);
        }
        
        /* 处理老图片 */
        if(!empty($data['old_desc'])){
        	$old_data_photo =[];
        	foreach ($data['old_desc'] as $key => $value) {
        		$old_data_photo[]=['id'=>$key,"desc"=>$value];
        	}
        	Core::loadAddonModel("GoodsPhoto")->saveAll($old_data_photo);
        	unset($data['old_desc']);
        }

        $result = Core::loadAddonModel($this->name)->saveObject($data);

		if($result){

			/* 处理商品图片 */
	        if(!empty($data['url'])){

	        	$data_photo=[];

	        	foreach ($data['url'] as $key => $value) {

	        		if(empty($value)) continue;

	        		/* 处理商品缩略图 */
					$thumb=$this->explode_thumb($value,120,120);

	        		$data_photo[]=["goods_id"=>isset($data['id'])?$data['id']:$result,"url"=>$value,"desc"=>$data['desc'][$key],"thumb"=>$thumb];
	        	}
	        	Core::loadAddonModel("GoodsPhoto")->saveAll($data_photo);
	        }

	        $GoodsAttrModel = Core::loadAddonModel("GoodsAttr");
	        /* 处理属性*/
	        if(!empty($data['goods_type'])){

	        	$data_goods_attr=$data_cache=[];

				foreach ($data['attr_value_list'] as $key => $value) {

					if(in_array($data['attr_id_list'][$key]."_".$value, $data_cache) || empty($value)) continue;

					$data_cache[] =  $data['attr_id_list'][$key]."_".$value;

					$data_goods_attr[]=["goods_id"=>isset($data['id'])?$data['id']:$result,"attr_id"=>$data['attr_id_list'][$key],"attr_value"=>$value,"attr_price"=>$data['attr_price_list'][$key]];
				}

				if(isset($data['id'])){
					$list = $GoodsAttrModel->getList(["where"=>["goods_id"=>$data['id']]]);

					foreach ($data_goods_attr as $key => $value) {
						foreach ($list as $k => $v) {
							if($value['attr_id'] == $v['attr_id'] && $value['attr_value'] == $v['attr_value']){  
								$data_goods_attr[$key]['id']=$v['id'];
								unset($list[$k]);
								break;
							}
						}
					}

					$delete_ids=[];
					foreach ($list as $key => $value) {
						$delete_ids[]=$value['id'];
					}

					!empty($delete_ids) && $GoodsAttrModel->deleteObject(["id"=>["exp"," in(".implode(",", $delete_ids).")"]],true);
					
				}

		        $GoodsAttrModel->saveAll($data_goods_attr);
		    }

		    if(empty($data['goods_type']) && isset($data['id'])){

		    	$GoodsAttrModel->deleteObject(['goods_id'=>$data['id']],true);

		    }
			 
			return [RESULT_SUCCESS,"操作成功",url('mall/Goods/index')];
		}
		return [40045,"操作失败"]; 
	}
	// 删除分两种，一种是真实删除，一种是软删除 更改is_delete字段
	public function delGoods($data){
		if(isset($data['delete']) && $data['delete']==1){  // 直接删除
			$result = self::deleteObject(['id'=>$data['id']],true);
		}
		else{ 
			$result = self::deleteObject(['id'=>$data['id']],false,"is_delete");
		}
		if($result){
			return [0,"操作成功",url('mall/Goods/index')];
		}
		return [40045,"操作失败"]; 
	}

	private function explode_thumb($img,$width="200",$height="200"){

		if(empty($img)) return "";

		$arr = explode(".",$img);

    	$file_name = basename($img,".".end($arr))."_thumb.".end($arr);

    	$image = \think\Image::open('.'.$img);

    	$dir_name='./data/uploads/thumbs/'.date('Ym',time());

		if(!file_exists($dir_name)){

			mkdir($dir_name,0777,true);

		}

		$image->thumb($width, $height)->save($dir_name."/".$file_name);

		return '/data/uploads/thumbs/'.date('Ym',time()).'/'.$file_name;

	}
}